import { AUTH_TOKEN } from "../constant";

function handleRouter() {
  const path = window.location.pathname;
  const token =
    localStorage.getItem(AUTH_TOKEN) || sessionStorage.getItem(AUTH_TOKEN);
  const pathname = window.location.pathname;
  if (token) {
    // 检查 token 是否存在并且是否有效
    const parts = token.split(".");
    if (parts.length >= 2) {
      // 检查 base64 编码的字符串是否正确
      const payloadEncoded = parts[1];
      if (
        payloadEncoded.length % 4 === 0 &&
        /^[\w+/=]+$/.test(payloadEncoded)
      ) {
        // 解析 token 中的 payload 部分
        const payload: { exp: number } = JSON.parse(atob(payloadEncoded)) as {
          exp: number;
        };
        // 检查 token 是否过期
        if (payload.exp * 1000 < Date.now()) {
          localStorage.removeItem(AUTH_TOKEN);
          window.location.assign("/login");
          return;
        }
      }
    } else {
      console.error("Invalid token: not enough parts");
      localStorage.removeItem(AUTH_TOKEN);
      window.location.assign("/login");
      return;
    }
  }
  if (!token && path !== "/login") {
    window.location.assign("/login");
    return;
  }
  if (token && path === "/login") {
    window.location.assign("/home");
    return;
  }
  if (pathname === path) return;
  window.location.assign(path);
}

function RouterGuard(Cpm: React.FC<any>) {
  return function Component(props: any) {
    handleRouter();
    return <Cpm {...props} />;
  };
}

export default RouterGuard;
